﻿using System.Windows.Controls;
using KinonekoSoftware.Studio.Resources.Converters;
using NAudio.MediaFoundation;

namespace KinonekoSoftware.Studio.Contents
{

    [Associate(View = typeof(ObjectSelectorView), ViewModel = typeof(ObjectSelectorViewModel))]
    public partial class ObjectSelectorView
    {
        private ObjectSelectorViewModel _vm;
        
        public ObjectSelectorView()
        {
            InitializeComponent();
        }

        protected override void OnLoaded()
        {
            var vm           = _vm = ViewModel<ObjectSelectorViewModel>();
            var res          = Resources["ObjectNameSelector"];
            var template = Resources["Universal"] as DataTemplate;

            if (vm is null)
            {
                return;
            }
            
            if (res is ObjectNameSelectorConverter selector)
            {
                selector.Selector = vm.Selector;
            }

            //
            //
            Items.ItemTemplate = template;
            Items.ItemsSource      =  vm.Collection;
            Items.SelectionMode    =  vm.IsMultipleSelection ? SelectionMode.Multiple : SelectionMode.Single;
            Items.SelectionChanged += OnSelectionChanged;
            
            //
            //
            base.OnLoaded();
        }
        
        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_vm is null)
            {
                return;
            }

            if (_vm.IsMultipleSelection)
            {
                _vm.SelectedItems = Items.SelectedItems;
            }
            else
            {
                _vm.SelectedItem = Items.SelectedItem;
            }
        }
    }
}